# coding: utf-8
import os

import cv2
import numpy as np
import wx
from cv2 import Mat
from matplotlib import pyplot as plt

from makeup.bitmap import MyFrame1
from makeup.ImgCoordinate import ImgCoordinate


def calculateMakeUpPoint(rightImgOVePoint, rightImgOVePointXy):
    """
    四点切图
    :param rightImgOVePoint:
    :param rightImgOVePointXy:
    :return:
    """
    imgForPoint = []

    x11 = rightImgOVePoint[1][0]
    x12 = rightImgOVePointXy[1][0]
    x1 = x11 + x12

    y11 = rightImgOVePoint[0][1]
    y12 = rightImgOVePointXy[0][1]
    y1 = y11 + y12

    y21 = rightImgOVePoint[2][1]
    y22 = rightImgOVePointXy[2][1]
    y2 = y21 + y22

    x21 = rightImgOVePoint[3][0]
    x22 = rightImgOVePointXy[3][0]
    x2 = x21 + x22

    imgForPoint.append((x1, y1))
    imgForPoint.append((x1, y2))
    imgForPoint.append((x2, y1))
    imgForPoint.append((x2, y2))

    return imgForPoint


class MakeUp(MyFrame1):

    def m_button2OnLeftDown(self, event):
        self.m_textCtrl12.Clear()
        self.collect_book_param()
        imgCoordinate = ImgCoordinate(self.makeUpWindowSizeHeight,self.makeUpWindowSizeWeight)

        offsetXY = []
        offsetDxDy = []
        offsetSxSy = []
        dealWith_BookType = 1
        if self.dealWithBookType == 0:
            dealWith_BookType = 0
        orignal_path = self.orignalPath
        self.m_textCtrl12.AppendText(f'拼板模式:{self.dealWithBookType}')
        samplingBool = False
        self.m_textCtrl12.AppendText('采样图片序号：' + self.samplingBookNo + ',一共处理图片数：' + str(
            len(os.listdir(orignal_path))) + os.linesep)
        if not samplingBool and len(self.samplingBookNo) != 0 and len(os.listdir(orignal_path)) >= int(
                self.samplingBookNo):
            print('-------------------------------------->')
            for ind, file in enumerate(os.listdir(orignal_path)):
                print(ind)
                if (ind + 1) == int(self.samplingBookNo):
                    filePath = os.path.join(orignal_path, file)
                    img: Mat = cv2.imdecode(np.fromfile(filePath, dtype=np.uint8), -1)
                    imgCoordinate.imgCoordinate(img)

                    offsetXY = imgCoordinate.fixedPointXY.copy()
                    offsetDxDy = imgCoordinate.fixedPoint.copy()
                    offsetSxSy = imgCoordinate.fixedPointSXSY.copy()
                    self.m_textCtrl12.AppendText(str(offsetXY))
                    self.m_textCtrl12.AppendText(os.linesep)
                    self.m_textCtrl12.AppendText(str(offsetDxDy))
                    self.m_textCtrl12.AppendText(os.linesep)
                    self.m_textCtrl12.AppendText(str(offsetSxSy))
                    self.m_textCtrl12.AppendText(os.linesep)
                    samplingBool = True

        if not samplingBool:
            self.m_textCtrl12.AppendText('请选择采样图片！' + os.linesep)
        if len(offsetXY) < 3:
            self.m_textCtrl12.AppendText('请选择采样点！' + os.linesep)
            return
        newFilePath = self.makeUpSavePath + os.altsep + self.makeUpSaveFolderName
        newFilePathSingle = self.makeUpSavePath + os.altsep + self.makeUpSaveFolderName+'sg1'
        newFilePathSingle2 = self.makeUpSavePath + os.altsep + self.makeUpSaveFolderName + 'sg2'
        if not os.path.isdir(newFilePath):
            os.makedirs(newFilePath)
            os.makedirs(newFilePathSingle)
            os.makedirs(newFilePathSingle2)
        fileList = os.listdir(orignal_path)
        fileLen = len(fileList)
        for ind, file in enumerate(fileList):

            if dealWith_BookType == 1 and ind % 2 == 1:  # 单页模式
                continue

            newImg = self.dealNewImg(imgCoordinate, file, offsetDxDy, offsetXY, offsetSxSy)
            mergeImg = True
            newImgPath = newFilePath + '\\' + self.makeUpSaveFolderName + '_' + str(ind) + '.jpg'
            newImgPath1 = newFilePathSingle + '\\' + self.makeUpSaveFolderName + '_' + str(ind) + '1.jpg'
            newImgPath2 = newFilePathSingle2 + '\\' + self.makeUpSaveFolderName + '_' + str(ind) + '2.jpg'
            if dealWith_BookType == 1:
                index = ind + 1
                if fileLen <= index:
                    index = 0
                newImg3 = self.dealNewImg(imgCoordinate, fileList[index], offsetDxDy, offsetXY, offsetSxSy,0)


                imgs = np.hstack((newImg3,newImg))
                #cv2.imwrite(newImgPath, imgs)
                cv2.imencode('.jpg', imgs)[1].tofile(newImgPath)
                cv2.imencode('.jpg', newImg)[1].tofile(newImgPath1)
                cv2.imencode('.jpg', newImg3)[1].tofile(newImgPath2)
                self.m_textCtrl12.AppendText(
                    '拼：' + newFilePath + '\\' + self.makeUpSaveFolderName + '_' + str(ind) + '.jpg' + os.linesep)

            if dealWith_BookType == 0 and ind < (fileLen - 1):
                newImg2 = self.dealNewImg(imgCoordinate, fileList[ind + 1], offsetDxDy, offsetXY, offsetSxSy,0)
                imgs = np.hstack((newImg2, newImg))
                mergeImg = True
                cv2.imencode('.jpg', newImg)[1].tofile(newImgPath1)
                cv2.imencode('.jpg', newImg2)[1].tofile(newImgPath2)
                #cv2.imwrite(newImgPath, imgs)
                cv2.imencode('.jpg', imgs)[1].tofile(newImgPath)
                self.m_textCtrl12.AppendText(
                    '拼：' + newFilePath + '\\' + self.makeUpSaveFolderName + '_' + str(ind) + '.jpg' + os.linesep)
            if not mergeImg:
                #cv2.imwrite(newImgPath, newImg)
                cv2.imencode('.jpg', newImg)[1].tofile(newImgPath)
                cv2.imencode('.jpg', newImg)[1].tofile(newImgPath1)
                self.m_textCtrl12.AppendText(
                    newFilePath + '\\' + self.makeUpSaveFolderName + '_' + str(ind) + '.jpg' + os.linesep)



    def dealNewImg(self, imgCoordinate, file, offsetDxDy, offsetXY, offsetSxSy, flip=1):
        filePath = os.path.join(self.orignalPath, file)
        self.m_textCtrl12.AppendText(filePath + os.linesep)
        # img: Mat = cv2.imread(filePath)
        img: Mat = cv2.imdecode(np.fromfile(filePath, dtype=np.uint8), -1)
        height, weight, type = img.shape
        print(f'height：{height}，weight：{weight}，file：{file}')
        if flip == 0:
            img = cv2.flip(img, 1)
        imgCoordinate.imgCoordinate(img, 1, offsetDxDy, offsetXY, offsetSxSy)
        rightImgOVePoint = imgCoordinate.fixedPoint.copy()
        rightImgOVePointXy = imgCoordinate.fixedPointXY.copy()
        fourPoint = self.calculateMakeUpFivePoint(rightImgOVePoint, rightImgOVePointXy)
        newImg = self.warpPerspectiveImg(img, fourPoint)
        if flip == 0:
            newImg = cv2.flip(newImg, 1)
        return newImg

    def calculateMakeUpFivePoint(self, rightImgOVePoint, rightImgOVePointXy):
        """
        ①---------------------⑤
        y1
        |
        ②-x1_1与①配对
        |
        |
        ③-x1_2与④配对
        |
        |
        ④--------------------
        :param rightImgOVePoint:
        :param rightImgOVePointXy:
        :return:
        """
        imgForPoint = []

        y11 = rightImgOVePoint[0][1]
        y12 = rightImgOVePointXy[0][1]
        y1 = y11 + y12

        x11 = rightImgOVePoint[1][0]
        x12 = rightImgOVePointXy[1][0]
        x1_1 = x11 + x12

        x11 = rightImgOVePoint[2][0]
        x12 = rightImgOVePointXy[2][0]
        x1_2 = x11 + x12

        y21 = rightImgOVePoint[3][1]
        y22 = rightImgOVePointXy[3][1]
        y2 = y21 + y22

        x21 = rightImgOVePoint[4][0]
        x22 = rightImgOVePointXy[4][0]
        x2 = x21 + x22

        imgForPoint.append((x1_1, y1))
        imgForPoint.append((x1_2, y2))
        imgForPoint.append((x2, y1))
        imgForPoint.append((x2, y2))

        return imgForPoint

    def warpPerspectiveImg(self, img, fourPoint):
        fourPoint = [list(e) for e in fourPoint]
        pts1 = np.float32(fourPoint)
        pts2 = np.float32([[0, 0], [0, 1905], [1131, 0], [1131, 1905]])
        M = cv2.getPerspectiveTransform(pts1, pts2)
        dst = cv2.warpPerspective(img, M, (1131, 1905))
        plt.subplot(122), plt.imshow(img), plt.title('Input')
        plt.subplot(121), plt.imshow(dst), plt.title('Output')
        return dst


class App(wx.App):

    def OnInit(self):  # 进入
        makeup = MakeUp()
        makeup.param_init()
        makeup.Show()
        return True

    def OnExit(self):  # 退出
        print("tuichu")
        return 0


def form():
    app = App()
    app.MainLoop()
